package proxy.cglibProxy;

import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Cglib子类代理工厂
 * 对UserDao在内存中动态构建一个子类对象
 *
 * @author Lenovo
 */
public class ProxyFactory implements MethodInterceptor {

    private Object target;
    private Callback callback;

    public ProxyFactory(Object target) {
        this.target = target;
    }


    /**
     * 给目标对象创建一个代理对象
     *
     * @return
     */
    public Object getProxyInstance() {
        //工具类
        Enhancer en = new Enhancer();
        //设置父类
        en.setSuperclass(target.getClass());
        //设置回调
        en.setCallback(this);
        //创建子类代理对象
        return en.create();

    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("pre..." + method.getName());
        Object returnValue = method.invoke(target, args);
        System.out.println("after..." + method.getName());

        return returnValue;
    }

    public static void main(String[] args) {
        Function1 target = new Function1();
        Function1 proxy = (Function1) new ProxyFactory(target).getProxyInstance();
        System.out.println(proxy.getClass());
        proxy.function();
    }
}
